// GAME
var Game = function(){

	this.STATE = 'MENU';
	this.PLAYER = '';
	this.TIME = 0;
	this.SCORE = 0;
	this.currentTick = 0;
	this.warning = 4;
	this.timeBeforeWarning = 0;
	this.bonus = null;
	this.bonusState = false;
	this.bonusTimer = 0;
	this.p1 = null;
	this.enemies = [];
	this.enemiesMenu = [];
	this.nbEnemies = 0;

	this.highScoreRequest = false; // jm
	
	this.cashPeriod = 10;
	this.xFollower = 0;
	this.yFollower = 0;

	this.nbType = 3;

	this.offSetFollowers = 1;

	this.eventListenersSet = false;

	this.init = function(p) {
		// Player
		this.PLAYER = p;
		this.p1 = new Player();		
		this.p1.init(this);
		this.xFollower = this.p1.bounds.x;
		this.yFollower = this.p1.bounds.y;
		this.p1.context = ctx;
		var iT = 0;
		while(++iT <= this.nbType){
			this.enemies[iT] = [];
			this.enemiesMenu[iT] = [];
			this.generateEnemy(5, iT);
			this.generateEnemyInMenu(5, iT)
		}

		window.addEventListener('deviceorientation', handleOrientation);
		
		if (!this.eventListenersSet) {
			var that = this;

			/**
			 * Game over buttons
			**/

			$('tryagain').addEventListener('touchstart', function() {
				that.clear();
				that.STATE = 'GAME';
			});
			$('tryagain').addEventListener('click', function() {
				that.clear();
				that.STATE = 'GAME';
			});

			$('highscores').addEventListener('touchstart', function() {
				var player_name = $s('#letter_1').innerHTML + $s('#letter_2').innerHTML + $s('#letter_3').innerHTML;
				db.addScore({name:player_name, score: that.SCORE, time:that.TIME});

				that.clear();
				that.STATE = "SCORES";
			});
			$('highscores').addEventListener('click', function() {
				var player_name = $s('#letter_1').innerHTML + $s('#letter_2').innerHTML + $s('#letter_3').innerHTML;
				db.addScore({name:player_name, score:that.SCORE, time:that.TIME});

				that.clear();
				that.STATE = "SCORES";
			});
		}
	}

	this.clear = function() {
		this.TIME = 0;
		this.SCORE = 0;
		this.currentTick = 0;
		this.nbEnemies = 0;
		this.init("P1");
		this.highScoreRequest = false;
	}

	this.update = function(){
		if (this.STATE == 'MENU') {
			var iT = 0;
			while(++iT <= this.nbType){
				var iE = 0;
				while(++iE <= this.enemiesMenu[iT].length){
					this.enemiesMenu[iT][iE-1].update();
				}
			}
			this.input();
		}
		else if (this.STATE == 'GAME') {
			// Bonus
			if (!this.bonusState) {
				this.xFollower = this.p1.bounds.x;
				this.yFollower = this.p1.bounds.y;
			}
			if (this.bonus != null) {
				if (this.bonusTimer >= this.bonus.bonusType.time) {
					this.bonus.desactivate(this.bonus.bonusType);
					this.bonus = null;
					this.bonusState = false;
					this.bonusTimer = 0;
				}
			}
			this.move();
			this.currentTick++;
			if (this.currentTick > 60) {
				if(this.bonus == null && !this.bonusState && this.TIME % 2) {
					this.createBonus();
				}
				this.TIME++;
				if (this.bonusState) this.bonusTimer++;
				if (this.TIME % this.cashPeriod == 0) this.SCORE += 100;
				this.currentTick = 0;
			}
			this.p1.update();

			var iT = 0;
			while(++iT <= this.nbType){
				var iE = 0;
				while(++iE <= this.enemies[iT].length){
					this.enemies[iT][iE-1].update();
				}
			}

			if (!this.p1.alive) this.STATE ='GAMEOVER';
		}
		this.render();
	}

	// Mouvement des éléments du jeu
	this.move = function() {	
	}

	//Affichage
	this.render = function(){
		if (this.STATE == 'MENU') this.renderMenu();
		else if (this.STATE == 'GAMEOVER') {			
			this.renderGameOver();
		}
		else if (this.STATE == 'GAME') {
			this.renderMap();
			// this.renderFPS();
			this.renderHUD();
			this.p1.render();

			if(this.bonus != null)
				this.bonus.render(ctx);
			
			var iT = 0;
			while(++iT <= this.nbType){
				for (var iE = 0; iE < this.enemies[iT].length; iE++) {
					this.enemies[iT][iE].render();
				}
			}

			if (this.p1.type != 0 ) {
				$('canvas').style.boxShadow = '0px 0px 20px rgba('	+COLORS['r'][this.p1.avoiders]+', '
																	+COLORS['g'][this.p1.avoiders]+', '
																	+COLORS['b'][this.p1.avoiders]+', 1)';
			}
		}
	}

	//Gestion des inputs		
	this.input = function(){
		
		/*if( this.STATE == 'GAMEOVER' || this.STATE == 'MENU' ) {
			if( getKey('h').state ) {
				self.location.href = 'scoring.php';
			}
			if(MOUSE.dbclic)
				self.location.href = 'scoring.php';
		}*/
		
		/*if(MOUSE.clic) {
			if (this.STATE == 'MENU') {
				//document.body.removeChild( $('container') );
				this.STATE = 'GAME';
			}
			if (this.STATE == 'GAMEOVER') {
				this.TIME = 0;
				this.SCORE = 0;
				this.currentTick = 0;
				this.nbEnemies = 0;
				this.STATE = 'GAME';
				this.init("P1");
				this.highScoreRequest = false;
			}
		}*/
	}

	// FUNCTION RENDER 
	this.renderMenu = function() {
		ctx.fillStyle = "#000";
		ctx.fillRect(0, 0, MAX_WIDTH, MAX_HEIGHT);
		ctx.fillStyle = "#FFF";
		var GameTitle = '.RGB';

		var title = '[TOUCH TO START]        [DOUBLE TAP TO SEE HIGH SCORES]';

		ctx.font = 68 + "pt MolotRegular";
		ctx.fillText(GameTitle, (MAX_WIDTH/2)-GameTitle.length*26, 110);
		ctx.font = 28 + "pt MolotRegular";
		ctx.fillText(title, (MAX_WIDTH/2)-title.length*9, MAX_HEIGHT-100);
		// // Rectangle
		ctx.strokeStyle = 'rgba(255, 255, 255, 1)';
		ctx.strokeRect(MAX_WIDTH/2-75, MAX_HEIGHT/2-80, 150, 150);
		var iT = 0;
		while(++iT <= this.nbType){
			for (var iE = 0; iE < this.enemiesMenu[iT].length; iE++) {
				this.enemiesMenu[iT][iE].render(ctx[this.PLAYER]);
			}
		}
	}

	this.renderGameOver = function() {
	
		var appreciation;

		$('score').innerHTML = this.SCORE;
		$('chrono').innerHTML = convertTimeToString(this.TIME);

		if 		(this.SCORE > 0) 		appreciation = 'Good game, looser...';
		else if (this.SCORE > 5000) 	appreciation = 'So, you seem to be dead, noob...';
		else if (this.SCORE > 20000) 	appreciation = 'You are on the right way dude !';
		else if (this.SCORE > 40000) 	appreciation = 'Awesome ! You are so gorgeous !';
		else if (this.SCORE > 60000) 	appreciation = 'Wait... What ?!!!';
		else if (this.SCORE > 80000) 	appreciation = 'Holy sh** !!!';
		else if (this.SCORE > 100000) 	appreciation = 'Good Game Master.';

		$('appreciation').innerHTML = appreciation;

		var alpha = ['A','B','C','D','E','F','G','H','I','J','K','L','M','N','O','P','Q','R','S','T','U','V','W','X','Y','Z'];

		for (var i in $s('#name .letter')) {
			try {
				$s('#name .letter')[i].addEventListener('touchstart', function() {
					this.setAttribute('data-idx', parseInt(this.getAttribute('data-idx')) + 1);
					this.innerHTML = alpha[this.getAttribute('data-idx')];
				});
				$s('#name .letter')[i].addEventListener('click', function() {
					this.setAttribute('data-idx', parseInt(this.getAttribute('data-idx')) + 1);
					this.innerHTML = alpha[this.getAttribute('data-idx')];
				});
			} catch(e) {}
		}
	}

	this.renderMap = function() {
		ctx.shadowColor = "#000";
		ctx.shadowBlur = 0;
		ctx.fillStyle = "rgba(0,0,0,0.3)";
		ctx.fillRect(0, 0, MAX_WIDTH, MAX_HEIGHT);
		this.renderWarning();
		
		var axeX = 0;
		var axeY = 0;
	}

	this.renderHUD = function() {
		var timer = convertTimeToString(this.TIME);
		var score = '';
		if (this.SCORE < 100) score = '000000';
		else if (this.SCORE < 1000) score = '0000';
		else if (this.SCORE < 10000) score = '000';
		else if (this.SCORE < 100000) score = '00';
		score += this.SCORE;
		ctx.font = 12 + "pt MolotRegular";
		ctx.fillStyle = 'rgba('	+COLORS['r'][this.p1.avoiders]+', '
								+COLORS['g'][this.p1.avoiders]+', '
								+COLORS['b'][this.p1.avoiders]+', .1)';
		if (this.bonus != null) {
			if (this.bonus.type == "money" && this.bonus.disappear) ctx.fillStyle = 'rgba(229, 73, 16, 0.8)';
			else if (this.bonus.type == "nocolor" && this.bonus.disappear) ctx.fillStyle = 'rgba(255, 255, 255, 0.8)';
		}		
		ctx.fillText(score, (MAX_WIDTH/2)-score.length*15, MAX_HEIGHT - 30);
		ctx.fillStyle = 'rgba('	+COLORS['r'][this.p1.avoiders]+', '
								+COLORS['g'][this.p1.avoiders]+', '
								+COLORS['b'][this.p1.avoiders]+', .1)';
		if (this.bonus != null) {
			if (this.bonus.type == "nocolor" && this.bonus.disappear) ctx.fillStyle = 'rgba(255, 255, 255, 0.8)';
		}
		ctx.fillText(timer, (MAX_WIDTH/2)-timer.length*13, 60);		
	}

	this.renderWarning = function() {
		switch (this.warning) {	
			case 0 :  	var warning = 'Pick a color !!';
						break;
								
			case 1 : 	var warning = 'Kill Greens !!';
						break;

			case 2 : 	var warning = 'Kill Blues !!';
						break;

			case 3 : 	var warning = 'Kill Reds !!';
						break;

			default : 	var warning = '';
						break;
		}
		
		ctx.font = 12 + "pt MolotRegular";
		ctx.fillStyle = 'rgba('	+COLORS['r'][this.p1.avoiders]+', '
												+COLORS['g'][this.p1.avoiders]+', '
												+COLORS['b'][this.p1.avoiders]+', 1)';
		ctx.shadowColor = "#000";
		ctx.shadowBlur = 20;
		ctx.fillText(warning, (MAX_WIDTH/2)-warning.length*13, 0 + MAX_HEIGHT/2);
		if (this.TIME - this.timeBeforeWarning >= 2) this.warning = 4;
	}

	this.renderFPS = function(){
		ctx.fillStyle = "#000";
		ctx.fillRect(MAX_WIDTH - 60, 15, 20, 20);

		ctx.font = 12 + "pt MolotRegular";
		ctx.fillStyle = "rgba(255, 255, 255, .3)";
		ctx.fillText(this.fps+' fps', MAX_WIDTH - 60, 30);
	}

	this.drawLine = function(xFrom,yFrom,xTo,yTo) {
		ctx.strokeStyle = "#888";
		ctx.beginPath();
		ctx.moveTo(xFrom,yFrom);
		ctx.lineTo(xTo,yTo);
		ctx.closePath();
		ctx.stroke();
	}

	this.generateEnemy = function(nbEnemy, type){
		var iE = 0;
		while(++iE <= nbEnemy){
			this.nbEnemies++;
			//Ajoute un enemy au tableau et récupère l'id inséré + 1 
			var thatEnemy = this.enemies[type].push(new Enemy());
			//Initialise l'enemy inséré dans le tableau
			this.enemies[type][thatEnemy-1].init(Math.random()*MAX_WIDTH,Math.random()*MAX_HEIGHT,3,type);	
		}
	}

	
	this.createBonus = function() {
		var listOfBonus = [
							'money','money','money','money',
							'gravity','gravity','gravity',
							'freeze','freeze',
							'nocolor'							 
						];
		// var listOfBonus = ['gravity'];
		var random = Math.random();
		var seuilRandom = 0.6;
		if (this.p1.bounds.radius < 10) {
			var type = 'life';
			seuilRandom = 0.2;
		}
		else var type = listOfBonus[Math.round(rand(0,listOfBonus.length-1))];

		if (random >= seuilRandom && this.p1.type != 0) {
			this.bonus = new Bonus();
			this.bonus.init(type);
		}
	}

	this.generateEnemyInMenu = function(nbEnemy, type){
		var iE = 0;
		while (++iE <= nbEnemy) {
			//Ajoute un enemy au tableau et récupère l'id inséré + 1 
			var thatEnemy = this.enemiesMenu[type].push(new Enemy());
			//Initialise l'enemy inséré dans le tableau
			var x = rand((MAX_WIDTH/2-70),(MAX_WIDTH/2+70));
			var y = rand(((MAX_HEIGHT/2-80)),((MAX_HEIGHT/2+40)));
			this.enemiesMenu[type][thatEnemy-1].init(x,y,3,type);			
		}
	}

};
var game = new Game();